package com.hbfec.mqttmanager.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.messaging.Message;

import java.io.Serializable;
import java.util.Date;

public class MessageEntity implements Serializable{
    private static final long serialVersionUID = 1L;
    private Logger log = Logger.getLogger(MessageEntity.class);
    private String topic;
    private String sender;
    private String receiver;
    private String payload;
    private Date created;

    public MessageEntity(){
        super();
    }

    public MessageEntity(String topic, String sender, String receiver, String payload, Date created) {
        super();
        this.topic = topic;
        this.sender = sender;
        this.receiver = receiver;
        this.payload = payload;
        this.created = created;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public String getReceiver() {
        return receiver;
    }

    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    public String getPayload() {
        return payload;
    }

    public void setPayload(String payload) {
        this.payload = payload;
    }


    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public static MessageEntity parse(Message message)
    {
        MessageEntity m = new MessageEntity();
        m.setTopic(message.getHeaders().get("mqtt_topic", String.class));
        m.setPayload(message.getPayload().toString());
        m.setCreated(new Date(message.getHeaders().get("timestamp", Long.class)));

        try{
            JSONObject payload = JSON.parseObject(message.getPayload().toString());
            m.setSender(payload.getString("sender"));
            m.setReceiver(payload.getString("receiver"));
        }catch (Exception ex)
        {
            //TODO
        }

        return m;
    }

}
